package com.gdyx.app.web.web;

import com.gdyx.app.web.model.*;
import com.gdyx.app.web.svc.*;
import com.gdyx.app.web.util.Condition;
import com.gdyx.app.web.util.MpsFunDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by Y_Coffee on 2017/8/3.
 */
public class BaseController {
    @Autowired
    MpsDeptRoleSvc mpsDeptRoleSvc;
    @Autowired
    MpsOrgUserSvc mpsOrgUserSvc;
    @Autowired
    MpsUserSvc mpsUserSvc;
    @Autowired
    MpsRoleSvc mpsRoleSvc;
    @Autowired
    MpsOrgSvc mpsOrgSvc;
    @Autowired
    HttpServletRequest request;
    @Autowired
    MpsUserRoleSvc mpsUserRoleSvc;
    @Autowired
    MpsDeptUserSvc mpsDeptUserSvc;
    @Autowired
    MpsDeptSvc mpsDeptSvc;
    @Autowired
    MpsRoleFunSvc mpsRoleFunSvc;
    @Autowired
    MpsRoleOptSvc mpsRoleOptSvc;
    @Autowired
    MpsFunSvc mpsFunSvc;
    @Autowired
    MpsFunOptSvc mpsFunOptSvc;

    public List<MpsFunDto> doMenus(List<MpsFun> list, String curUrl) {
        List<MpsFunDto> dtos = new ArrayList<>();
        //增加首页
        MpsFunDto idto = new MpsFunDto();
        idto.setId(UUID.randomUUID().toString().trim().toUpperCase());
        idto.setName("系统首页");
        idto.setHref("/");
        if (curUrl.isEmpty() || curUrl.equalsIgnoreCase("/")) {
            idto.setActive(true);
        } else {
            idto.setActive(false);
        }
        dtos.add(idto);

        list.stream().forEach(item -> {
            if (null == item.getParent() || item.getParent().isEmpty()) {
                MpsFunDto dto = new MpsFunDto();
                dto.CopyValuesFromMpsFun(item);

                if (curUrl.equalsIgnoreCase(dto.getHref())) {
                    dto.setActive(true);
                    System.out.println(item.getHref() + "," + curUrl);
                } else {
                    dto.setActive(false);
                }
                dto.setChildren(doChildren(dto, list, curUrl));
                dtos.add(dto);
            }
        });
        return dtos;
    }

    public List<MpsFunDto> doChildren(MpsFunDto parent, List<MpsFun> list, String curUrl) {
        List<MpsFunDto> dtos = new ArrayList<>();
        list.stream().forEach(item -> {
            if (item.getParent().equalsIgnoreCase(parent.getId())) {
                MpsFunDto dto = new MpsFunDto();
                dto.CopyValuesFromMpsFun(item);

                if (curUrl.equalsIgnoreCase(dto.getHref())) {
                    dto.setActive(true);
                    parent.setActive(true);
                } else {
                    dto.setActive(false);
                }

                dto.setChildren(doChildren(dto, list, curUrl));
                dtos.add(dto);
            }
        });
        return dtos;
    }

    public void DoRoot(List<MpsFun> list, List<MpsFun> det) {
        list.stream().forEach(item -> {
            if (item.getParent().isEmpty()) {
                det.add(item);
                doChi(item.getId(), list, det);
            }
        });
    }

    public void doChi(String parent, List<MpsFun> src, List<MpsFun> det) {
        src.stream().forEach(item -> {
            if (!(item.getParent().isEmpty()) && item.getParent().equalsIgnoreCase(parent)) {
                det.add(item);
                doChi(item.getId(), src, det);
            }
        });
    }

    public void DoRootDept(List<MpsDept> list, List<MpsDept> det) {
        list.stream().forEach(item -> {
            List<String> role = new ArrayList<>();
            MpsOrg mpsOrg = mpsOrgSvc.findMpsOrgById(item.getOrgId());
            item.setOrgId(mpsOrg.getName());
            List<MpsDeptRole> webDeptRoleList = mpsDeptRoleSvc.findDeptRoleByDid(item.getId());
            webDeptRoleList.stream().forEach(wdr -> {
                MpsRole mpsRole = mpsRoleSvc.findMpsRoleById(wdr.getRoleId());
                role.add(mpsRole.getName());
            });
            String[] roleStrs = role.toArray(new String[role.size()]);
            item.setRoles(roleStrs);
            if (item.getParent().isEmpty()) {
                det.add(item);
                doChiDept(item.getId(), list, det);
            }
        });
    }

    public void doChiDept(String parent, List<MpsDept> src, List<MpsDept> det) {
        src.stream().forEach(item -> {
            if (!(item.getParent().isEmpty()) && item.getParent().equalsIgnoreCase(parent)) {
                det.add(item);
                doChiDept(item.getId(), src, det);
            }
        });
    }

    public Condition ruleBuild(String connnctor, String column, String operator, java.lang.Object value, String type) {
        Condition condition = new Condition();
        try {
            condition.setConnector(connnctor);
            condition.setColumn(column);
            condition.setOperator(operator);
            condition.setType(type);
            condition.setValue(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return condition;
    }

    /**
     * @param uid
     * @return 传入uid下归属机构拥有的所有用户
     */
    public List<MpsUser> toOrgUsers(String uid) {
        //获取用户归属机构
        List<MpsOrgUser> mpsOrgUserListByUid = mpsOrgUserSvc.findMpsOrgUsersByUid(uid);
        //获取该用户机构下的机构所有用户
        List<MpsUser> orgAllUser = new ArrayList<>();
        mpsOrgUserListByUid.stream().forEach(moubu -> {
            List<MpsOrgUser> mpsOrgUserListByOid = mpsOrgUserSvc.findMpsOrgUsersByOid(moubu.getOrgId());
            mpsOrgUserListByOid.stream().forEach(moubo -> {
                orgAllUser.add(mpsUserSvc.findMpsUserById(moubo.getUserId()));
            });
        });
        //去重
        List<MpsUser> resultUser = new ArrayList<>(new HashSet<>(orgAllUser));
        List<MpsUser> userList = new ArrayList<>();
        for (MpsUser mpsUser : resultUser) {
            if("0".equals(String.valueOf(mpsUser.getStatus()))){
                userList.add(mpsUser);
            }
        }
        return userList;
    }

    /**
     * @param uid
     * @return uid下构建的依据orgId动态SQL数据Map
     */
    public Map<String, Object> sqlWithOrg(String uid, String column) {
        List<MpsOrgUser> mpsOrgUserListByUid = mpsOrgUserSvc.findMpsOrgUsersByUid(uid);
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        for (int i = 0; i < mpsOrgUserListByUid.size(); i++) {
            if (i == 0) {
                conditions.add(ruleBuild("and", column, "=", mpsOrgUserListByUid.get(i).getOrgId(), "S"));
            } else {
                conditions.add(ruleBuild("or", column, "=", mpsOrgUserListByUid.get(i).getOrgId(), "S"));
            }
            map.put("conditions", conditions);
        }
        return map;
    }

       //获取当前用户的机构S
    public List<MpsOrg>  GetOrgByUser(){
        MpsUser user = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        List<MpsOrgUser> mpsOrgUsersByUid = mpsOrgUserSvc.findMpsOrgUsersByUid(user.getId());
        Iterator<MpsOrgUser> iterator = mpsOrgUsersByUid.iterator();
        while (iterator.hasNext()) {
            MpsOrgUser mpsOrgUser = iterator.next();
            if(mpsOrgUser.getOrgchk()!=0 || mpsOrgUser.getUserchk()!=0){
                iterator.remove();
            }
        }
        List<MpsOrg> mpsOrgs=new ArrayList<>();
        if(mpsOrgUsersByUid!=null){
            Map<String, Object> map = new HashMap<>();
            List<Condition> conditions = new ArrayList<>();
            for (int i = 0; i < mpsOrgUsersByUid.size(); i++) {
                if(i==0){
                    conditions.add(ruleBuild("and", "id", "=",mpsOrgUsersByUid.get(i).getOrgId(), "S"));
                }else {
                    conditions.add(ruleBuild("or", "id", "=",mpsOrgUsersByUid.get(i).getOrgId(), "S"));
                }
            }
            map.put("conditions", conditions);
            mpsOrgs= mpsOrgSvc.findMpsOrgs(map);
        }
        return mpsOrgs;
    }


    //获取用户所在机构的角色
    public List<MpsRole>  GetRoleByUserAndOrg(String userId,String orgId){
        //获得用户下的所有角色
        List<MpsUserRole> userRoleByUid = mpsUserRoleSvc.findUserRoleByUid(userId);
        List<MpsRole> mpsRoles=new ArrayList<>();
        if(userRoleByUid!=null & userRoleByUid.size()>0){
            //筛选机构
            Map<String, Object> map = new HashMap<>();
            List<Condition> conditions = new ArrayList<>();
            List<String> idslist=new ArrayList<>();
            for (int i = 0; i < userRoleByUid.size(); i++) {
                idslist.add(userRoleByUid.get(i).getRoleId());
            }
            conditions.add(ruleBuild("and", "id", "in",idslist, "S"));
            conditions.add(ruleBuild("and", "orgId", "=",orgId, "S"));
            map.put("conditions", conditions);
            mpsRoles = mpsRoleSvc.findMpsRoles(map);
        }
        return mpsRoles;
    }
    //获取当前用户所在机构的部门
    public List<MpsDept>  GetDeptByUserAndOrg(String userId,String orgId){
        //获得用户下的部门
        List<MpsDeptUser> deptUserByUid = mpsDeptUserSvc.findDeptUserByUid(userId);
        List<MpsDept> mpsDepts=new ArrayList<>();
        if(deptUserByUid!=null & deptUserByUid.size()>0){
            Map<String, Object> map = new HashMap<>();
            List<Condition> conditions = new ArrayList<>();
            List<String> idsList=new ArrayList<>();
            for (MpsDeptUser mpsDeptUser : deptUserByUid) {
                idsList.add(mpsDeptUser.getDeptId());
            }
            conditions.add(ruleBuild("and", "id", "in",idsList, "S"));
            conditions.add(ruleBuild("and", "orgId", "=",orgId, "S"));
            map.put("conditions", conditions);
            mpsDepts = mpsDeptSvc.findMpsDepts(map);
        }
        return mpsDepts;
    }


    //获取当前用户下的所拥有机构下的用户
    public List<MpsUser>  GetUserByOrg(String orgId){
        //依据机构获取用户
        List<MpsOrgUser> mpsOrgUsersByOid = mpsOrgUserSvc.findMpsOrgUsersByOid(orgId);
        Iterator<MpsOrgUser> iterator = mpsOrgUsersByOid.iterator();
        while (iterator.hasNext()) {
            MpsOrgUser mpsOrgUser = iterator.next();
            if(mpsOrgUser.getOrgchk()!=0 || mpsOrgUser.getUserchk()!=0){
                iterator.remove();
            }
        }
        List<MpsUser> mpsUsers=new ArrayList<>();
        if(mpsOrgUsersByOid!=null & mpsOrgUsersByOid.size()>0){
            Map<String, Object> map = new HashMap<>();
            List<Condition> conditions = new ArrayList<>();
            for (int i = 0; i < mpsOrgUsersByOid.size(); i++) {
                if (i == 0) {
                    conditions.add(ruleBuild("and", "id", "=", mpsOrgUsersByOid.get(i).getUserId(), "S"));
                } else {
                    conditions.add(ruleBuild("or", "id", "=", mpsOrgUsersByOid.get(i).getUserId(), "S"));
                }
            }
            map.put("conditions", conditions);
            mpsUsers = mpsUserSvc.findMpsUsers(map);
        }
        return mpsUsers;
    }


    //根据用户id和机构ID获取所有权限
    public void GetFunByUser(String userId,String orgId){
        if (StringUtils.isEmpty(orgId)){
            return;
        }
        List<MpsFun> allMpsFuns = new ArrayList<>();
        List<MpsFunOpt> allMpsOpts = new ArrayList<>();
        Set<String> allRoles = new HashSet<>();

        //当前用户的角色
        List<MpsRole> mpsRoles = GetRoleByUserAndOrg(userId,orgId);
        mpsRoles.stream().forEach(role -> {
            allRoles.add(role.getId());
        });

        //当前用户的部门
        List<MpsDept> mpsDepts = GetDeptByUserAndOrg(userId,orgId);
        mpsDepts.stream().forEach(dept -> {
            List<MpsDeptRole> mpsDeptRoleList = mpsDeptRoleSvc.findDeptRoleByDid(dept.getId());
            mpsDeptRoleList.stream().forEach(wdr -> {
                allRoles.add(wdr.getRoleId());
            });
        });

        //依据角色查询功能
        allRoles.stream().forEach(role -> getFunByrid(role).forEach(wrfa -> allMpsFuns.add(mpsFunSvc.findMpsFunById(wrfa.getFunId()))));
        //处理重复
        List<MpsFun> mpsFuns = new ArrayList<>(new HashSet<>(allMpsFuns));
        //依据角色查询操作
        allRoles.stream().forEach(role -> getOptByrid(role).forEach(wrfa -> allMpsOpts.add(mpsFunOptSvc.findMpsFunOptById(wrfa.getOptId()))));
        //处理重复
        List<MpsFunOpt> mpsFunOpts = new ArrayList<>(new HashSet<>(allMpsOpts));
        request.getSession().setAttribute("WEBOPTS", mpsFunOpts);
        request.getSession().setAttribute("WEBFUNS", mpsFuns);
        request.getSession().setAttribute("ADMIN_MENUS", doMenus(mpsFuns, "/"));
    }

    /*
       依据roleId获取功能权限id
       */
    public List<MpsRoleFun> getFunByrid(String roleId) {
        List<MpsRoleFun> mpsRoleFunAuths =new ArrayList<>();
        try {
            //构建条件查询
            Map<String, Object> map = new HashMap<>();
            List<Condition> conditions = new ArrayList<>();
            conditions.add(ruleBuild("and", "roleId", "=", roleId, "S"));
            map.put("conditions", conditions);
            //依据关联表查询该角色拥有的功能权限
            mpsRoleFunAuths = mpsRoleFunSvc.findMpsRoleFuns(map);
            return mpsRoleFunAuths;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mpsRoleFunAuths;
    }

    /*
      依据roleId获取操作权限id
      */
    public List<MpsRoleOpt> getOptByrid(String roleId) {

        List<MpsRoleOpt> MpsRoleOpts = new ArrayList<>();
        try {
            //构建条件查询
            Map<String, Object> map = new HashMap<>();
            List<Condition> conditions = new ArrayList<>();
            conditions.add(ruleBuild("and", "roleId", "=", roleId, "S"));
            map.put("conditions", conditions);
            //依据关联表查询该角色拥有的功能权限
            MpsRoleOpts = mpsRoleOptSvc.findMpsRoleOpts(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return MpsRoleOpts;
    }
}


